import { ipcMain, dialog } from 'electron';
import fs from 'fs/promises';
import path from 'path';

/**
 * @description 注册文件操作相关的 IPC 处理函数
 */
function handleFile() {
  /**
   * 处理渲染进程发起的文件保存对话框请求
   * @param {Electron.IpcMainInvokeEvent} event - IPC 事件对象
   * @param {object} options - 对话框选项
   * @returns {Promise<{canceled: boolean, filePath?: string}>}
   */
  ipcMain.handle('dialog:saveFile', async (event, options = {}) => {
    try {
      const result = await dialog.showSaveDialog({
        title: options.title || '保存文件',
        defaultPath: options.defaultPath || '',
        filters: options.filters || [
          { name: '所有文件', extensions: ['*'] }
        ]
      });
      
      return result;
    } catch (error) {
      console.error('文件保存对话框错误:', error);
      return { canceled: true, error: error.message };
    }
  });

  /**
   * 处理渲染进程发起的文件打开对话框请求
   * @param {Electron.IpcMainInvokeEvent} event - IPC 事件对象
   * @param {object} options - 对话框选项
   * @returns {Promise<{canceled: boolean, filePaths?: string[]}>}
   */
  ipcMain.handle('dialog:openFile', async (event, options = {}) => {
    try {
      const result = await dialog.showOpenDialog({
        title: options.title || '打开文件',
        defaultPath: options.defaultPath || '',
        filters: options.filters || [
          { name: '所有文件', extensions: ['*'] }
        ],
        properties: options.properties || ['openFile']
      });
      
      return result;
    } catch (error) {
      console.error('文件打开对话框错误:', error);
      return { canceled: true, error: error.message };
    }
  });

  /**
   * 处理渲染进程发起的写入文件请求
   * @param {Electron.IpcMainInvokeEvent} event - IPC 事件对象
   * @param {string} filePath - 文件路径
   * @param {string} content - 文件内容
   * @param {object} options - 写入选项
   * @returns {Promise<{success: boolean, error?: string}>}
   */
  ipcMain.handle('file:write', async (event, filePath, content, options = {}) => {
    try {
      // 确保目录存在
      await fs.mkdir(path.dirname(filePath), { recursive: true });
      
      // 写入文件
      await fs.writeFile(filePath, content, {
        encoding: options.encoding || 'utf8',
        ...options
      });
      
      return { success: true };
    } catch (error) {
      console.error('写入文件失败:', error);
      return { success: false, error: error.message };
    }
  });

  /**
   * 处理渲染进程发起的读取文件请求
   * @param {Electron.IpcMainInvokeEvent} event - IPC 事件对象
   * @param {string} filePath - 文件路径
   * @param {object} options - 读取选项
   * @returns {Promise<{success: boolean, data?: string, error?: string}>}
   */
  ipcMain.handle('file:read', async (event, filePath, options = {}) => {
    try {
      const content = await fs.readFile(filePath, {
        encoding: options.encoding || 'utf8',
        ...options
      });
      
      return { success: true, data: content };
    } catch (error) {
      console.error('读取文件失败:', error);
      return { success: false, error: error.message };
    }
  });

  /**
   * 处理渲染进程发起的检查文件是否存在请求
   * @param {Electron.IpcMainInvokeEvent} event - IPC 事件对象
   * @param {string} filePath - 文件路径
   * @returns {Promise<{success: boolean, exists: boolean, error?: string}>}
   */
  ipcMain.handle('file:exists', async (event, filePath) => {
    try {
      await fs.access(filePath);
      return { success: true, exists: true };
    } catch (error) {
      if (error.code === 'ENOENT') {
        return { success: true, exists: false };
      }
      console.error('检查文件存在性失败:', error);
      return { success: false, exists: false, error: error.message };
    }
  });

  /**
   * 处理渲染进程发起的删除文件请求
   * @param {Electron.IpcMainInvokeEvent} event - IPC 事件对象
   * @param {string} filePath - 文件路径
   * @returns {Promise<{success: boolean, error?: string}>}
   */
  ipcMain.handle('file:delete', async (event, filePath) => {
    try {
      await fs.unlink(filePath);
      return { success: true };
    } catch (error) {
      console.error('删除文件失败:', error);
      return { success: false, error: error.message };
    }
  });

  /**
   * 处理渲染进程发起的获取文件信息请求
   * @param {Electron.IpcMainInvokeEvent} event - IPC 事件对象
   * @param {string} filePath - 文件路径
   * @returns {Promise<{success: boolean, data?: object, error?: string}>}
   */
  ipcMain.handle('file:stat', async (event, filePath) => {
    try {
      const stats = await fs.stat(filePath);
      return { 
        success: true, 
        data: {
          size: stats.size,
          isFile: stats.isFile(),
          isDirectory: stats.isDirectory(),
          mtime: stats.mtime,
          ctime: stats.ctime,
          atime: stats.atime
        }
      };
    } catch (error) {
      console.error('获取文件信息失败:', error);
      return { success: false, error: error.message };
    }
  });
}

// 导出处理函数
export { handleFile };